package com.coderitl.springmvc.handle;


import com.coderitl.springmvc.exception.AgeException;
import com.coderitl.springmvc.exception.NameException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalHandleException {
    // 定义处理异常的方法,当发生异常时,执行此方法

    /**
     * 处理 NameException 类型的异常
     * 参数:
     * Exception: 表示 Controller 抛出的异常对象
     *
     * @ExceptionHandler: 表示此方法处理异常
     * 属性: value 时异常的类型
     * 位置: 方法的上面
     *  value = Class<? extends Throwable>[] value() default {};
     */
    @ExceptionHandler(value = NameException.class)
    public ModelAndView nameExceptionHandler(Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("tip", "用户名必须是: coder-itl");
        mv.setViewName("NameError");
        return mv;
    }

    @ExceptionHandler(value = AgeException.class)
    public ModelAndView ageExceptionHandler(Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("tip", "年龄必须是小于35!");
        mv.setViewName("AgeError");
        return mv;
    }

    @ExceptionHandler
    public ModelAndView defaultExceptionHandler(Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("tip", "default: uname=coder-itl,age=18");
        mv.setViewName("DefaultError");
        return mv;
    }
}
